package com.gxnu.edu.cn.ttxxt.controller;

import com.gxnu.edu.cn.ttxxt.entity.Messages;
import com.gxnu.edu.cn.ttxxt.entity.Users;
import com.gxnu.edu.cn.ttxxt.mapper.UserRepository;
import com.gxnu.edu.cn.ttxxt.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/text")
    public ResponseEntity<Messages> sendTextMessage(@RequestBody Map<String, Object> request) {
        try {
            // 参数校验
            if (!request.containsKey("senderId") || !request.containsKey("receiverId") ||
                    !request.containsKey("isGroup") || !request.containsKey("content")) {
                return ResponseEntity.badRequest().body(null);
            }

            Long senderId = Long.parseLong(request.get("senderId").toString());
            Long receiverId = Long.parseLong(request.get("receiverId").toString());
            Boolean isGroupFlag = Boolean.parseBoolean(request.get("isGroup").toString());
            Integer isGroup = isGroupFlag ? 1 : 0;
            String content = request.get("content").toString();
            Users users = userRepository.selectById1(senderId);
            Users users1 = userRepository.selectById1(receiverId);
            String ip1 = users.getIp();
            String ip2 = users1.getIp();

            String subnetMask = "255.255.255.0";

            // 判断两个 IP 是否在同一内网
            boolean isInSameSubnet = isInSameSubnet(ip1, ip2, subnetMask);
            if (isInSameSubnet) {
                System.out.println("发送者和接收者的 IP 在同一内网");
            } else {
                System.out.println("发送者和接收者的 IP 不在同一内网");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            }
            // 业务逻辑处理
            Messages messages = messageService.sendTextMessage(senderId, receiverId, content, isGroup);
            return ResponseEntity.ok(messages);

        } catch (Exception e) {
            // 关键修改：记录详细异常信息
            System.err.println(e);

            // 返回错误信息而不是空对象
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .header("Error-Message", e.getMessage())
                    .body(null);
        }
    }

    /**
     * 判断两个 IP 地址是否在同一个内网
     * @param ip1 第一个 IP 地址
     * @param ip2 第二个 IP 地址
     * @param subnetMask 子网掩码
     * @return 如果在同一个内网返回 true，否则返回 false
     */
    private boolean isInSameSubnet(String ip1, String ip2, String subnetMask) {
        try {
            InetAddress inetAddress1 = InetAddress.getByName(ip1);
            InetAddress inetAddress2 = InetAddress.getByName(ip2);
            InetAddress inetSubnetMask = InetAddress.getByName(subnetMask);

            byte[] bytes1 = inetAddress1.getAddress();
            byte[] bytes2 = inetAddress2.getAddress();
            byte[] maskBytes = inetSubnetMask.getAddress();

            for (int i = 0; i < bytes1.length; i++) {
                if ((bytes1[i] & maskBytes[i]) != (bytes2[i] & maskBytes[i])) {
                    return false;
                }
            }
            return true;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return false;
        }
    }

    @PostMapping("/file")
    public ResponseEntity<?> sendFileMessage(@RequestBody Map<String, Object> request) {
        Long senderId = Long.parseLong(request.get("senderId").toString());
        Long receiverId = Long.parseLong(request.get("receiverId").toString());
        String content = request.get("content").toString();
        Integer isGroup = Integer.parseInt(request.get("isGroup").toString());
        Long fileId = Long.parseLong(request.get("fileId").toString());

        Messages messages = messageService.sendFileMessage(senderId, receiverId, content, isGroup, fileId);
        return ResponseEntity.ok(messages);
    }

    @PostMapping("/shake")
    public ResponseEntity<?> sendShakeMessage(@RequestBody Map<String, Object> request) {
        Long senderId = Long.parseLong(request.get("senderId").toString());
        Long receiverId = Long.parseLong(request.get("receiverId").toString());
        Integer isGroup = Integer.parseInt(request.get("isGroup").toString());

        Messages messages = messageService.sendShakeMessage(senderId, receiverId, isGroup);
        return ResponseEntity.ok(messages);
    }

    @GetMapping("/history")
    public ResponseEntity<List<Messages>> getChatHistory(@RequestParam Long userId,
                                                         @RequestParam Long contactId,
                                                         @RequestParam Integer isGroup,
                                                         @RequestParam(defaultValue = "0") int page,
                                                         @RequestParam(defaultValue = "20") int size) {
        List<Messages> messages = messageService.getChatHistory(userId, contactId, isGroup, page, size);
        return ResponseEntity.ok(messages);
    }

    @GetMapping("/unread")
    public ResponseEntity<?> getUnreadMessages(@RequestParam Long userId) {
        List<Messages> messages = messageService.getUnreadMessages(userId);
        return ResponseEntity.ok(messages);
    }

    @PostMapping("/mark-read")
    public ResponseEntity<?> markMessagesAsRead(@RequestBody Map<String, Object> request) {
        Long userId = Long.parseLong(request.get("userId").toString());
        Long contactId = Long.parseLong(request.get("contactId").toString());
        Integer isGroup = Integer.parseInt(request.get("isGroup").toString());

        messageService.markMessagesAsRead(userId, contactId, isGroup);
        return ResponseEntity.ok("消息已标记为已读");
    }
}
    